﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using zichan.BLL;
using zichan.Entity;
using zichan.Models;

namespace zichan.Controllers
{
    public class StaffController : BaseController
    {
        // GET: Admin/Staff

        [HttpGet]
        public ActionResult Index(string name, string departmentName, int? roleId, int? page, int? pageSize, int? pageCount, int? selectedPage)
        {
            ViewBag.name = name;
            ViewBag.roleId = roleId;
            ViewBag.departmentName = departmentName;
            page = page ?? 1;
            pageSize = pageSize ?? 10;
            if (selectedPage.HasValue)
                page = selectedPage;
            if (pageCount.HasValue)
                page = page <= pageCount ? page : pageCount;
            if (page < 1) page = 1;
            ViewBag.page = page;
            ViewBag.pageSize = pageSize;
            ViewBag.selectedPage = selectedPage;
            List<SelectListItem> items = new List<SelectListItem> { new SelectListItem { Value = "10", Text = "10" }, new SelectListItem { Value = "20", Text = "20" }, new SelectListItem { Value = "50", Text = "50" }, new SelectListItem { Value = "100", Text = "100" } };
            ViewBag.pageSizes = new SelectList(items, "Value", "Text", ViewBag.pageIndex);

            ViewBag.Roles = new SelectList(RoleService.List(), "Id", "Name", roleId);
            return View(StaffService.StaffList(name, departmentName, roleId,pageSize.Value, page.Value));
        }


        //// 添加职员
        //// get Admin/Staff/Create
        //[HttpGet]
        //public ActionResult Create()
        //{
        //    return View();
        //}


        //[HttpPost]
        //public ActionResult Create(StaffModel model)
        //{
        //    if (!ModelState.IsValid)
        //        return View();
        //    Staff staff = new Staff();
        //    string err = StaffService.StaffAdd(staff);
        //    if (string.IsNullOrEmpty(err))
        //        TempData["alert"] = "success#操作成功";
        //    else
        //        TempData["alert"] = "error#" + err;

        //    return RedirectToAction("index");
        //}

        // 授权管理
        // get:Admin/Staff/Auth

        [HttpGet]
        public ActionResult Auth(int id)
        {
            ViewBag.Id = id;
            return View(StaffService.StaffRoleList(id));
        }

        // 添加职员授权
        // get Admin/Staff/Create
        [HttpGet]
        public ActionResult CreateAuth(int id)
        {
            List<int> rids = StaffService.StaffRoleList(id).Select(o => o.RoleId).ToList();
            var list = RoleService.List().Where(o => !rids.Contains(o.Id)).Select(o => new { o.Id, o.Name }).ToList();
            ViewBag.Roles = new SelectList(list, "Id", "Name");
            return View(new CreateAuthModel() { StaffId = id });
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult CreateAuth(CreateAuthModel model)
        {
            if (!ModelState.IsValid)
            {
                List<int> rids = StaffService.StaffRoleList(model.StaffId).Select(o => o.RoleId).ToList();
                var list = RoleService.List().Where(o => !rids.Contains(o.Id)).Select(o => new { o.Id, o.Name }).ToList();
                ViewBag.Roles = new SelectList(list, "Id", "Name");
                return View(model);
            }

            string err = StaffService.StaffRoleAdd(model.StaffId, model.RoleId);
            if (string.IsNullOrEmpty(err))
                TempData["alert"] = "success#操作成功";
            else
                TempData["alert"] = "error#" + err;

            return RedirectToAction("Auth", new { id = model.StaffId });
        }


        [HttpGet]
        public ActionResult DeleteAuth(int id, int staffid)
        {
            string err = StaffService.StaffRoleRemove(id);
            if (string.IsNullOrEmpty(err))
                TempData["alert"] = "success#操作成功";
            else
                TempData["alert"] = "error#" + err;

            return RedirectToAction("Auth", new { id = Request["staffid"] });
        }

       public ActionResult TreeIndex()
        {
            return View(StaffService.TreeStaff());
        }
       
        public ActionResult TreeAuth(int id)
        {
            ViewBag.Id = id;
            return PartialView(StaffService.StaffRoleList(id));
        }
        [HttpGet]
        public PartialViewResult TreeCreateAuth(int id)
        {
            List<int> rids = StaffService.StaffRoleList(id).Select(o => o.RoleId).ToList();
            var list = RoleService.List().Where(o => !rids.Contains(o.Id)).Select(o => new { o.Id, o.Name }).ToList();
            ViewBag.Roles = new SelectList(list, "Id", "Name");
            ViewBag.Id = id;
            return PartialView(new CreateAuthModel() { StaffId = id });
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public PartialViewResult TreeCreateAuth(CreateAuthModel model)
        {
            if (!ModelState.IsValid)
            {
                List<int> rids = StaffService.StaffRoleList(model.StaffId).Select(o => o.RoleId).ToList();
                var list = RoleService.List().Where(o => !rids.Contains(o.Id)).Select(o => new { o.Id, o.Name }).ToList();
                ViewBag.Roles = new SelectList(list, "Id", "Name");
                return PartialView(model);
            }

            if (model.pIds==null && model.StaffId == 0)
            {
                TempData["alert"] = "error#请先选择职员";
            }
            if (model.pIds != null)
            {
                List<int> staffIds = Array.ConvertAll<string, int>(model.pIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), o => Convert.ToInt32(o)).ToList();
                int retNo = StaffService.StaffRoleBatchsAdd(model.pIds, model.RoleId, ConfigurationManager.ConnectionStrings["ZichanDBContext"].ConnectionString);
                if (retNo >= 0)
                    TempData["alert"] = "success#操作成功";
                else
                    TempData["alert"] = "error#无法添加";

                ViewBag.Id = model.StaffId;
            }
           else
            {
                 string err = StaffService.StaffRoleAdd(model.StaffId, model.RoleId);
                if (string.IsNullOrEmpty(err))
                    TempData["alert"] = "success#操作成功";
                else
                    TempData["alert"] = "error#"+err;
            }
            return PartialView("TreeAuth", StaffService.StaffRoleList(model.StaffId));
        }
        public ActionResult TreeDeleteAuth(int id, int staffid)
        {
            string err = StaffService.StaffRoleRemove(id);
            if (string.IsNullOrEmpty(err))
                TempData["alert"] = "success#操作成功";
            else
                TempData["alert"] = "error#" + err;

            ViewBag.Id = staffid;
            return PartialView("TreeAuth", StaffService.StaffRoleList(staffid));
        }

        public PartialViewResult TreeDepartmentAuth(int departmentId, int? page, int? pageSize, int? pageCount, int? selectedPage)
        {
            page = page ?? 1;
            pageSize = pageSize ?? 10;
            if (selectedPage.HasValue)
                page = selectedPage;
            if (pageCount.HasValue)
                page = page <= pageCount ? page : pageCount;
            if (page < 1) page = 1;
            ViewBag.page = page;
            ViewBag.pageSize = pageSize;
            ViewBag.selectedPage = selectedPage;
            List<SelectListItem> items = new List<SelectListItem> { new SelectListItem { Value = "10", Text = "10" }, new SelectListItem { Value = "20", Text = "20" }, new SelectListItem { Value = "50", Text = "50" }, new SelectListItem { Value = "100", Text = "100" } };
            ViewBag.pageSizes = new SelectList(items, "Value", "Text", ViewBag.pageIndex);

            ViewBag.departmentId = departmentId;
            return PartialView(DepartmentRoleService.DepartmentRoleList(departmentId, page.Value, pageSize.Value));
        }
        public PartialViewResult TreeDepartmentCreateAuth(int departmentId)
        {
            ViewBag.departmentId = departmentId;
            List<int> rids = DepartmentRoleService.DepartmentRoleList(departmentId);
            var list = RoleService.List().Where(o => !rids.Contains(o.Id)).Select(o => new { o.Id, o.Name }).ToList();
            ViewBag.Roles = new SelectList(list, "Id", "Name");
            return PartialView();
        }
        [HttpPost]
        public PartialViewResult TreeDepartmentCreateAuth(DepartmentRole model)
        {
            model.RoleName = RoleService.Get(model.RoleId).Name;
            string constr = ConfigurationManager.ConnectionStrings["ZichanDBContext"].ConnectionString;
            string err = DepartmentRoleService.Add(model, constr);
            if (string.IsNullOrEmpty(err))
            {
                TempData["alert"] = "success#授权成功";
            }
            else
            {
                TempData["alert"] = "error#授权失败";
            }
            return PartialView("TreeDepartmentAuth", DepartmentRoleService.DepartmentRoleList(model.DepartmentId, 1, 10));
        }
        public PartialViewResult TreeDepartmentDeleteAuth(int departmentId, int roleId, int id)
        {
            string constr = ConfigurationManager.ConnectionStrings["ZichanDBContext"].ConnectionString;
            string err = DepartmentRoleService.Delete(departmentId, roleId, id, constr);
            if (string.IsNullOrEmpty(err))
            {
                TempData["alert"] = "success#成功删除";
            }
            else
            {
                TempData["alert"] = "error#删除失败";
            }
           return PartialView("TreeDepartmentAuth", DepartmentRoleService.DepartmentRoleList(departmentId, 1, 10));
        }
    }
}